<template>
  <div>
    <div class="content">
      <div class="content__left">
        <div
          :class="{
            content__left__item: true,
            'content__left__item--active': item.tab === currentTab,
          }"
          v-for="item in categories"
          :key="item.id"
          @click="handleTabChange(item.tab)"
        >
          {{ item.name }}
        </div>
      </div>
      <div class="content__right">
        <template v-for="(item) in list" :key="item.id">
            <ProducsInfoVue :item="item"></ProducsInfoVue>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import { get } from "../utils/request";
import ProducsInfoVue from "./ProducsInfo.vue";
import { useRoute } from "vue-router";
import { reactive,toRefs,watchEffect,ref } from "vue";
const categories = [
  { name: "全部商品", tab: "all" },
  { name: "秒杀", tab: "seckill" },
  { name: "新鲜水果", tab: "fruit" },
];
// tab切换逻辑，点击的时候传入当前tab,然后改变currenttable的值，
const useTableEffect = () => {
  const currentTab = ref(categories[0].tab);
  const handleTabChange = (tab) => {
    currentTab.value = tab;
  };
  return { currentTab, handleTabChange };
};

// 获取右侧商品信息逻辑
const getProductInfoEffect = (currentTab, shopId)=>{
    const content = reactive({ list:[] });
    const getContentData = async (tab) => {
        const result = await get( `/api/shop/${shopId}/products`,{
            tab: currentTab.value
        } )
        if(result?.errno === 0 && result?.data?.length){
            content.list = result.data;
        }
    }
    /**
     * watchEffect
     * 不需要手动传入依赖
     * 每次初始化时会执行一次回调函数来自动获取依赖
     * 无法获取到原值，只能得到变化后的值
     */
    watchEffect( ()=> {getContentData()} )
    const { list } = toRefs(content);
    return {list}
}

export default {
  components: {
     ProducsInfoVue, 
  },
  setup() {
    const route = useRoute();
    const shopId = route.params.id;
    const { currentTab, handleTabChange } = useTableEffect();
    const { list } = getProductInfoEffect(currentTab,shopId);
    return {
      currentTab,
      categories,
      handleTabChange,
      list
    };
  },
};
</script>
<style lang="scss" scoped>
body,
html {
  height: 100%;
}
* {
  margin: 0;
  padding: 0;
}

.content {
  display: flex;
  position: absolute;
  top: 150px;
  left: 0px;
  right: 0px;
  bottom: 50px;
  &__left {
    height: 460px;
    flex: 0.7;
    // background-color: red;
    background-color: #f5f5f5;
    &__item {
      height: 40px;
      line-height: 40px;
      text-align: center;
      &--active {
        background-color: #fff;
      }
    }
  }
  &__right {
    flex: 2;
    margin-left: 16px;
  }
}
</style>
